import 'vant/es/toast/style'
import {
  showFailToast,
  showSuccessToast,
  type UploaderAfterRead,
  type UploaderBeforeRead,
  type UploaderFileListItem,
} from 'vant'
import { useUserStore } from '@/stores'
import { putAvatarAPI } from '@/api/user'
interface UseUploadReturnType {
  onOversize: () => void
  beforeRead: UploaderBeforeRead
  afterRead: UploaderAfterRead
}
export default function (): UseUploadReturnType {
  const userStore = useUserStore()
  const user = userStore.user
  // 限制上传图片大小
  const onOversize = () => {
    showFailToast('文件大小不能超过 500kb')
  }
  // 上传前置处理图片格式
  const beforeRead: UploaderBeforeRead = (file) => {
    if (!/image\/\w+/.test((file as File).type)) {
      showFailToast('请上传图片格式的文件')
      return false
    }
    return true
  }
  // 上传图片
  const afterRead: UploaderAfterRead = async (file) => {
    // 创建 FormData 对象准备上传文件
    const formData = new FormData()
    formData.append('file', (file as UploaderFileListItem).file as File)
    try {
      const response = await fetch('/api/common/upload', {
        method: 'POST',
        body: formData,
      })
      const data = await response.json()

      if (data.code === 1) {
        await putAvatarAPI({ id: user.id, avatar: data.data })
        showSuccessToast('上传成功')
      } else {
        showFailToast('上传失败，请稍后再试')
      }
    } catch (error) {
      console.log(error);
      showFailToast('上传过程中出现错误，请检查网络或稍后再试')
    }
  }
  return {
    onOversize,
    beforeRead,
    afterRead,
  }
}
